{% extends 'live/live_base.html' %}
{% load static %}

{% block title %}
    直播设置
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="row">
            <div class="col-2">
                <div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist"
                     aria-orientation="vertical">
                    <a class="nav-link active" id="v-pills-setting-tab" data-toggle="pill" href="#v-pills-setting"
                       role="tab" aria-controls="v-pills-setting" aria-selected="true">直播设置</a>
                    <a class="nav-link" id="v-pills-help-tab" data-toggle="pill" href="#v-pills-help"
                       role="tab" aria-controls="v-pills-help" aria-selected="false">直播帮助</a>
                </div>
            </div>
            <div class="col-10">
                <div class="tab-content" id="v-pills-tabContent">
                    <div class="tab-pane fade show active" id="v-pills-setting" role="tabpanel"
                         aria-labelledby="v-pills-setting-tab">
                        <div class="row"
                             style="border: #4d78ff solid 1px; border-radius: 10px; margin-top: 10px; margin-bottom: 10px">
                            <div class="col-auto" style="margin: 20px">
                                <div class="row">
                                    <button type="button" class="btn btn-outline-primary" id="getAddressButton"
                                            {% if live_room.is_open %} disabled{% endif %}
                                            onclick="getLiveSetting('{% url 'get_address' %}','#getAddressButton', '#rtmpAddress')">
                                        获取推流地址
                                    </button>
                                </div>
                                <br>
                                <div class="row">
                                    <button type="button" class="btn btn-outline-primary" id="getKeyButton"
                                            {% if live_room.is_open %} disabled{% endif %}
                                            onclick="getLiveSetting('{% url 'get_key' %}','#getKeyButton', '#rtmpKey')">
                                        获取推流密钥
                                    </button>
                                </div>
                            </div>
                            <div class="col-auto" style="border: #63a8ff">
                                <div class="row" style="margin: 20px">
                                    <div class="col-auto">
                                        <ul class="list-group list-group-flush">
                                            <li class="list-group-item">推流地址: &nbsp; <span
                                                    class="text-danger" id="rtmpAddress">{% if ad %}
                                                {{ ad }}&nbsp;&nbsp;<span class="copyVideo"
                                                                          style="color:#10b7ff;cursor:pointer;"
                                                                          onclick="copyVideoUrl('#rtmpAddress')">复制</span>{% else %}
                                                (点击按钮获取){% endif %}</span>

                                            </li>
                                            <li class="list-group-item">推流密钥: &nbsp; <span
                                                    class="text-danger" id="rtmpKey">{% if key %}
                                                {{ key }}&nbsp;&nbsp;<span class="copyVideo"
                                                                           style="color:#10b7ff;cursor:pointer;"
                                                                           onclick="copyVideoUrl('#rtmpKey')">复制</span> {% else %}
                                                (点击按钮获取){% endif %}</span>

                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto align-self-center">
                                <div class="alert alert-danger" role="alert">
                                    点击<span class="alert-link">开始直播</span>后在开始用<span class="alert-link">OBS</span>推流，
                                    否则<span class="alert-link">无法</span>推流
                                </div>
                            </div>
                        </div>
                        {#                    直播分区#}
                        <div class="row"
                             style="border: #4d78ff solid 1px; border-radius: 10px; margin-top: 10px; margin-bottom: 10px">
                            <div class="col-auto">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item">我的分区:&nbsp;&nbsp;&nbsp;
                                        <div class="row" style="display: inline-block">
                                            <div class="col-auto" style="display: inline-block">
                                                <span class="text-success">
                                                    {% if live_room.label %}
                                                        {{ live_room.label.father_label }}-->
                                                        {{ live_room.label }}
                                                    {% endif %}
                                                </span>
                                            </div>
                                        </div>
                                    </li>
                                    <li class="list-group-item">分区选择: &nbsp;
                                        <div class="row" style="display: inline-block">
                                            <div class="col-auto" style="display: inline-block;">
                                                <div class="input-group mb-1">
                                                    <div class="input-group-prepend">
                                                        <label class="input-group-text"
                                                               for="fatherLabelSelect">Options</label>
                                                    </div>
                                                    <select class="custom-select" id="fatherLabelSelect"
                                                            onchange="getSonLabel()">
                                                        <option selected
                                                                value="{{ live_room.label.father_label.id }}">
                                                            {% if live_room.label %}
                                                                {{ live_room.label.father_label }}{% else %}
                                                                Choose...{% endif %}</option>
                                                        {% for lb in father_label %}
                                                            {% if lb != live_room.label.father_label %}
                                                                <option value="{{ lb.id }}">{{ lb }}</option>
                                                            {% endif %}
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-auto" style="display: inline-block">
                                                <div class="input-group mb-1">
                                                    <div class="input-group-prepend">
                                                        <label class="input-group-text"
                                                               for="sonLabelSelect">Options</label>
                                                    </div>
                                                    <select class="custom-select" id="sonLabelSelect">
                                                        <option selected value="{{ live_room.label.name }}">
                                                            {% if live_room.label %}
                                                                {{ live_room.label }}{% else %}
                                                                Choose...{% endif %}</option>
                                                        {% for slb in son_label %}
                                                            {% if slb != live_room.label %}
                                                                <option value="{{ slb.name }}">{{ slb }}</option>
                                                            {% endif %}
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-auto align-self-center">
                                <button type="button" class="btn btn-outline-primary"
                                        onclick="submitLabel()">
                                    点击确定分区
                                </button>
                            </div>
                        </div>

                        {#                        更改直播间名#}
                        <div class="row"
                             style="border: #4d78ff solid 1px; border-radius: 10px; margin-top: 10px; margin-bottom: 10px">
                            <div class="col-auto">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item">直播间名:&nbsp;&nbsp;&nbsp;
                                        <div class="row" style="display: inline-block">
                                            <div class="col-auto" style="display: inline-block">
                                                {% if live_room.name %}
                                                    <span class="text-success">
                                                        {{ live_room.name }}
                                                        </span>
                                                {% else %}
                                                    <span class="text-danger">
                                                        请设置名称
                                                        </span>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </li>
                                    <li class="list-group-item">名称设置:&nbsp;&nbsp;&nbsp;
                                        <div class="row" style="display: inline-block">
                                            <div class="col-auto">
                                                <div class="input-group mb-1">
                                                    <input type="text" class="form-control" placeholder="房间名"
                                                           aria-label="Username" aria-describedby="basic-addon1"
                                                           id="roomName">
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-auto align-self-center">
                                <button type="button" class="btn btn-outline-primary"
                                        onclick="submitRoomName()">
                                    点击提交房间名
                                </button>
                            </div>
                        </div>
                        {#                    更改直播封面#}
                        <div class="row"
                             style="border: #4d78ff solid 1px; border-radius: 10px; margin-top: 10px; margin-bottom: 10px">
                            <div class="col-auto">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item">房间封面:&nbsp;&nbsp;&nbsp;
                                        {% if live_room.image %}
                                            <img src="{{ MEDIA_URL }}{{ live_room.image }}"
                                                 style="width: 270px;height: 168px;max-width: 100%;">
                                        {% else %}
                                            <span class="text-danger">请上传封面</span>
                                        {% endif %}
                                    </li>
                                    <li class="list-group-item">上传封面:&nbsp;&nbsp;&nbsp;
                                        <div class="row" style="display: inline-block">
                                            <div class="col-auto" style="display: inline-block">
                                                <div class="input-group mb-3">
                                                    <div class="custom-file">
                                                        <input type="file" class="custom-file-input"
                                                               id="roomImageInput" name="image" accept="image/*"
                                                               aria-describedby="imageInputAddon01"
                                                               onchange="CheckFile(this,['jpg', 'png','webp'])">
                                                        <label class="custom-file-label" for="imageInput">Choose
                                                            file</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-auto align-self-center">
                                <button type="button" class="btn btn-outline-primary"
                                        onclick="submitRoomImg()">
                                    点击提交封面
                                </button>
                            </div>
                        </div>
                        {#                    开启关闭直播#}
                        <div class="row">
                            {% if live_room.is_open %}
                                <div class="col-auto">
                                    <button type="button" class="btn btn-outline-danger" id="closeLiveButton"
                                            onclick="closeLive()" style="height: 50px">
                                        关闭直播
                                    </button>
                                    <a href="{% url 'play_live' %}?room_num={{ live_room.number }}">
                                        <button type="button" class="btn btn-outline-success"
                                                style="height: 50px">
                                            点击进入我的直播间
                                        </button>
                                    </a>
                                </div>
                                <div class="col-auto">
                                    <div class="alert alert-danger" role="alert">
                                        正在直播中，需要关闭直播才可重新获取<span class="alert-link">地址</span>与<span
                                            class="alert-link">密钥</span>
                                    </div>
                                </div>
                            {% else %}
                                <div class="col-auto">
                                    <button type="button" class="btn btn-outline-success" id="openLiveButton"
                                            onclick="openLive()" style="height: 50px">
                                        开启直播
                                    </button>
                                </div>
                                <div class="col-auto">
                                    <div class="alert alert-danger" role="alert">
                                        开始直播前请详细阅读<span class="alert-link">直播帮助</span>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                    {#                    直播帮助#}
                    <div class="tab-pane fade" id="v-pills-help" role="tabpanel"
                         aria-labelledby="v-pills-help-tab">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-auto">
                                    <h3 class="text-danger"><b>1.点击获取推流地址与密钥</b></h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-auto">
                                    <img src="/static/img/live_help/get_key.png">
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-auto">
                                    <h3 class="text-danger"><b>2.设置直播间信息</b></h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-auto">
                                    <img src="/static/img/live_help/set_info.png">
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-auto">
                                    <h3 class="text-danger"><b>3.点击开始直播</b></h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-auto">
                                    <img src="/static/img/live_help/start_live.png">
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-auto">
                                    <h3 class="text-danger"><b>4.打开OBS，并在设置中输入推流地址与推流密钥</b></h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-auto">
                                    <img src="/static/img/live_help/input_key.png">
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-auto">
                                    <h3 class="text-danger"><b>4.设置直播画面，并开始推流</b></h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-auto">
                                    <img src="/static/img/live_help/put_stream.png">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block custom_jss %}
    <script type="text/javascript">

        function copyVideoUrl(element_id) {
            var value = $(element_id).contents().filter(function () {
                return this.nodeType == 3;
            }).text().replace(/^\s*|\s*$/g, "");
            if (value == '(点击按钮获取)') {
                return
            }
            var success;
            var $temp = $("<input>");
            $("body").append($temp);
            $temp.val(value).select();
            try {
                success = document.execCommand("copy");
            } catch (e) {
                succeed = false;
            }
            if (success) {
                var $copySuccess = $("<div class='copy-tips'><div class=\"toast show\" role=\"alert\" aria-live=\"assertive\" aria-atomic=\"true\">\n" +
                    "  <div class=\"toast-header\">\n" +
                    "    <strong class=\"mr-auto\">复制成功</strong>\n" +
                    "    <button type=\"button\" class=\"ml-2 mb-1 close\" data-dismiss=\"toast\" aria-label=\"Close\">\n" +
                    "      <span aria-hidden=\"true\">&times;</span>\n" +
                    "    </button>\n" +
                    "  </div>\n" +
                    "  <div class=\"toast-body\">\n" +
                    "    " + value + ".\n" +
                    "  </div>\n" +
                    "</div></div>");
                $("body").find(".copy-tips").remove().end().append($copySuccess);
                $(".copy-tips").fadeOut(5000);
            }
            $temp.remove();
        }

        function closeLive() {
            $.ajax({
                type: 'POST',
                url: '{% url 'close_live' %}',
                dataType: 'json',
                async: true,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                    $('#closeLiveButton').attr({disabled: "disabled"});
                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }

            })
        }

        function CheckFile(obj, TypeArray) {
            var fileName = $(obj).val();
            $(obj).next('.custom-file-label').html(fileName);
            var array = TypeArray; //可以上传的文件类型
            if (obj.value == '') {
                alert("选择要上传的文件!");
                return false;
            } else {
                var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3];
                var isExists = false;
                for (var i in array) {
                    if (fileContentType.toLowerCase() == array[i].toLowerCase()) {
                        isExists = true;
                        return true;
                    }
                }
                if (isExists == false) {
                    $(obj).next('.custom-file-label').html('选择文件');
                    alert("上传文件类型不正确!");
                    return false;
                }
                return false;
            }
        }

        function submitRoomImg() {
            var image = $('#roomImageInput').get(0).files[0]; //获取上传的文件;//get(0)将Jquery对象转换为DOM对象

            var formData = new FormData();  //创建一个formData
            formData.append('image', image);

            $.ajax({
                type: 'POST',
                url: '{% url 'change_room_img' %}',
                dataType: 'json',
                async: false,
                cache: false,
                processData: false,//数据处理
                contentType: false,//内容类型
                data: formData,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }
            })
        }

        function submitRoomName() {
            const val = $('#roomName').val();
            if (val == '') {
                return
            }
            if (val.length >= 20) {
                alert('名字过长');
                return;
            }
            $.ajax({
                type: 'POST',
                url: '{% url 'change_room_name' %}',
                dataType: 'json',
                async: true,
                data: {'room_name': $('#roomName').val()},
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }
            })
        }

        function submitLabel() {
            const val = $('#sonLabelSelect').val();
            if (val == '') {
                return
            }
            $.ajax({
                type: 'POST',
                url: '{% url 'modify_label' %}',
                dataType: 'json',
                async: true,
                data: {'label_name': $('#sonLabelSelect').val()},
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }

            })
        }


        function getSonLabel() {
            $.ajax({
                type: 'POST',
                url: '{% url 'change_label' %}',
                dataType: 'json',
                async: true,
                data: {'label_id': $('#fatherLabelSelect').val()},
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (data) {
                    if (data['status'] == 'success') {
                        $('#sonLabelSelect').html('');
                        for (let items of data['data']) {
                            $('#sonLabelSelect').append('<option value="' + items + '">' + items + '</option>');
                        }
                    } else if (data['status'] == 'fail') {
                        $('#sonLabelSelect').html('');
                        $('#sonLabelSelect').html('<option>Choose...</option>');
                    }
                }

            })
        }

        function getLiveSetting(url, submit_button, msg_id) {
            $.ajax({
                type: 'POST',
                url: url,
                dataType: 'json',
                async: true,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                    $(submit_button).attr({disabled: "disabled"});
                },
                success: function (data) {
                    if (data.status == 'fail') {
                        $(msg_id).html(data.msg);
                    } else if (data.status == 'success') {
                        if (data.msg) {
                            html = '&nbsp;&nbsp;<span class="copyVideo"\n' +
                                'style="color:#10b7ff;cursor:pointer;"\n' +
                                'onclick="copyVideoUrl(\'' + msg_id + '\')">复制</span> ';
                            $(msg_id).html(data.msg + html);
                        }
                    }
                },
                complete: function () {
                    $(submit_button).removeAttr('disabled');
                },
            });
        }

        function openLive() {
            $.ajax({
                type: 'POST',
                url: '{% url 'open_live' %}',
                dataType: 'json',
                async: true,
                beforeSend: function (xhr, setting) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                    $('#openLiveButton').attr({disabled: "disabled"});

                },
                success: function (data) {
                    if (data['status'] == 'fail') {
                        alert(data['msg'])
                    }
                    window.location.reload()
                }

            })
        }
    </script>
{% endblock %}